<template>
  <div class="withdrawal-case-container">
    <a-card>
      <div class="page-header">
        <h2>撤委案管理</h2>
        <p class="page-description">管理撤委案件信息</p>
      </div>

      <div class="page-content">
        <div class="layout-container">
          <!-- 左侧：上传表单 (3/10) -->
          <div class="left-panel">
            <a-card title="Excel上传" class="upload-card">
              <a-form :model="formData" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="撤案文件" required>
                  <a-upload v-model:file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove" multiple
                    accept=".xlsx,.xls" :show-upload-list="true">
                    <a-button>
                      <upload-outlined />
                      选择Excel文件
                    </a-button>
                  </a-upload>
                  <div class="upload-tip">
                    支持上传多个Excel文件，每个文件可包含多个工作表
                  </div>
                </a-form-item>
                <!-- 
                这里 :wrapper-col="{ offset: 100, span: 16 }" 没有效果，
                是因为 offset 的单位是栅格（共24），100超出了范围。
                通常用于底部按钮对齐时，offset 设为 label-col 的宽度/栅格数。
                推荐写法如下，offset: 4 (label-col: { width: '100px' } 通常对应4栅格)。
              -->
                <!-- 
                offset 不能设置为100px，offset 只能是数字（栅格数，最大24），
                不能用像素单位。label-col 的宽度可以用px，但 offset 只能用数字。
                这里 offset: 4 通常对应 label-col: { width: '100px' } 的对齐效果。
              -->
                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                  <a-space>
                    <a-button type="primary" :disabled="fileList.length === 0" @click="previewExcel"
                      :loading="previewLoading" block>
                      <eye-outlined />
                      预览
                    </a-button>
                    <a-button type="primary" :disabled="fileList.length === 0" @click="processExcel"
                      :loading="processLoading" block>
                      <play-circle-outlined />
                      处理
                    </a-button>
                  </a-space>
                </a-form-item>
              </a-form>

              <div class="result-summary">
                <a-statistic title="总数据条数" :value="allTodayData.length" :value-style="{ color: '#1890ff' }" />
                <a-statistic title="涉及机构数" :value="organizationFilters.length" :value-style="{ color: '#52c41a' }" />
                <a-statistic title="日期分组数" :value="dateGroups.length" :value-style="{ color: '#fa8c16' }" />
              </div>

              <!-- 状态合并规则说明 -->
              <a-alert message="数据匹配和状态合并规则"
                description="系统通过机构、当事人姓名、身份证后六位、当事人手机号前三后四四个字段组合来识别同一条数据。如果找到匹配记录，则按以下规则合并状态：如果Excel或数据库中有一方状态为'已撤委案'，则合并后状态为'已撤委案'；只有当双方都为'待撤委案'时，合并后状态才为'待撤委案'。"
                type="info" show-icon :closable="false" class="status-merge-alert" />

            </a-card>
          </div>

          <!-- 右侧：处理结果 (7/10) -->
          <div class="right-panel">
            <a-card v-if="processedResults.length > 0" title="撤委案列表" class="result-card">
              <template #extra>
                <a-button type="primary" :icon="h(DownloadOutlined)" @click="exportToExcel" :loading="exportLoading">
                  导出Excel
                </a-button>
              </template>
              <div class="result-content">
                <!-- 按日期分组的Tab -->
                <a-tabs v-model:activeKey="activeTabKey" type="card" size="small">
                  <a-tab-pane v-for="dateGroup in dateGroups" :key="dateGroup.dateKey" :tab="dateGroup.tabTitle">
                    <a-table :columns="tableColumns" :data-source="dateGroup.data"
                      :pagination="{ pageSize: 20, showSizeChanger: true, showQuickJumper: true }" size="small" bordered
                      class="center-table" :scroll="{ x: 1000 }">
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.key === 'updateDate'">
                          <a-tag :color="isToday(record.updateDate) ? 'green' : 'default'">
                            {{ record.updateDate }}
                          </a-tag>
                        </template>
                        <template v-if="column.key === 'status'">
                          <a-tag :color="record.status === 1 ? 'success' : 'warning'"
                            :class="record.status === 1 ? 'status-withdrawn' : 'status-pending'">
                            {{ record.status === 1 ? '已撤委案' : '待撤委案' }}
                          </a-tag>
                        </template>
                        <template v-if="column.key === 'action'">
                          <a-button v-if="record.status !== 1" type="primary" size="small"
                            @click="handleUserDetail(record)" :loading="record.detailLoading">
                            用户详情
                          </a-button>
                          <span v-else class="action-withdrawn">-</span>
                        </template>
                      </template>
                    </a-table>
                  </a-tab-pane>
                </a-tabs>
              </div>
            </a-card>
          </div>
        </div>
      </div>
    </a-card>



    <!-- Excel预览弹框 -->
    <a-modal v-model:open="previewVisible" title="Excel预览" width="80%" :footer="null" :destroy-on-close="true">
      <div v-if="previewData">
        <a-tabs v-model:activeKey="previewActiveKey" type="card">
          <a-tab-pane v-for="(sheet, index) in previewData.sheets" :key="index.toString()" :tab="sheet.name">
            <a-table :columns="previewColumns" :data-source="sheet.data" :pagination="{ pageSize: 20 }" size="small"
              bordered :scroll="{ x: 1000 }" class="center-table" />
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>

    <!-- 撤委案确认弹框 -->
    <a-modal v-model:open="withdrawalConfirmVisible" title="撤委案确认" width="50%" :footer="null" :destroy-on-close="true">
      <div v-if="withdrawalConfirmData">
        <a-descriptions :column="1" bordered size="small">
          <a-descriptions-item label="符合规则人数">
            <a-statistic :value="withdrawalConfirmData.clientNum"
              :value-style="{ color: '#1890ff', fontSize: '24px' }" />
          </a-descriptions-item>
          <a-descriptions-item label="案件数">
            <a-statistic :value="withdrawalConfirmData.loanNum" :value-style="{ color: '#52c41a', fontSize: '24px' }" />
          </a-descriptions-item>
          <a-descriptions-item label="错误客户数" v-if="withdrawalConfirmData.errorClientNum > 0">
            <a-statistic :value="withdrawalConfirmData.errorClientNum"
              :value-style="{ color: '#ff4d4f', fontSize: '20px' }" />
          </a-descriptions-item>
        </a-descriptions>

        <div class="mt-4 text-center">
          <a-space size="large">
            <a-button @click="withdrawalConfirmVisible = false" :loading="withdrawalLoading">
              取消
            </a-button>
            <a-button type="primary" @click="confirmWithdrawal" :loading="withdrawalLoading">
              提交
            </a-button>
          </a-space>
        </div>
      </div>
    </a-modal>

    <!-- 用户详情弹框 -->
    <a-modal v-model:open="userDetailVisible" title="用户详情" width="60%" :footer="null" :destroy-on-close="true">
      <div v-if="userDetailData">
        <a-descriptions :column="2" bordered size="small">
          <a-descriptions-item label="姓名">{{ userDetailData.realName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="性别">{{ getGenderText(userDetailData.gender) }}</a-descriptions-item>
          <a-descriptions-item label="年龄">{{ userDetailData.age || '-' }}</a-descriptions-item>
          <a-descriptions-item label="身份证号">{{ userDetailData.idCard || '-' }}</a-descriptions-item>
          <a-descriptions-item label="手机号">{{ userDetailData.mobile || '-' }}</a-descriptions-item>
          <a-descriptions-item label="机构名称">{{ userDetailData.organization || '-' }}</a-descriptions-item>
          <a-descriptions-item label="委案商">{{ userDetailData.followStaffName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="贷款编号">{{ userDetailData.loanNo || '-' }}</a-descriptions-item>
          <a-descriptions-item label="贷款名称">{{ userDetailData.loanName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="逾期天数">{{ userDetailData.overdueDays || '-' }}天</a-descriptions-item>
          <a-descriptions-item label="产品类型">{{ userDetailData.productTypeName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="产品代码">{{ userDetailData.productTypeCode || '-' }}</a-descriptions-item>
          <a-descriptions-item label="应还金额">{{ formatMoney(userDetailData.totalShouldRepay) }}</a-descriptions-item>
          <a-descriptions-item label="未还金额">{{ formatMoney(userDetailData.totalNoRepayRepay) }}</a-descriptions-item>
          <a-descriptions-item label="已还金额">{{ formatMoney(userDetailData.realBackedRepay) }}</a-descriptions-item>
          <a-descriptions-item label="减免已还">{{ formatMoney(userDetailData.mitigateBackedRepay) }}</a-descriptions-item>
          <a-descriptions-item label="委案状态" :span="2">
            <a-tag :color="getDistributeStateColor(userDetailData.distributeState?.code)">
              {{ userDetailData.distributeState?.message || '-' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="贷款状态" :span="2">
            <a-tag :color="getLoanStateColor(userDetailData.state?.code)">
              {{ userDetailData.state?.message || '-' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="批次名称" :span="2">{{ userDetailData.batchName || '-' }}</a-descriptions-item>
          <a-descriptions-item label="催收时间" :span="2">{{ formatTime(userDetailData.urgeTime) }}</a-descriptions-item>
        </a-descriptions>

        <div v-if="userDetailData.records && userDetailData.records.length > 0" class="mt-4">
          <a-divider>可执行操作</a-divider>
          <a-space>
            <a-button type="primary" @click="handleWithdrawal(userDetailData)">
              确认撤委案
            </a-button>
            <a-button @click="userDetailVisible = false">
              关闭
            </a-button>
          </a-space>
        </div>
        <div v-else class="mt-4">
          <a-alert message="未找到该用户信息" description="系统中没有找到匹配的用户数据，无法执行撤委案操作。" type="warning" show-icon />
          <div class="mt-3 text-center">
            <a-button @click="userDetailVisible = false">
              关闭
            </a-button>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, h, watch } from 'vue';
import { message } from 'ant-design-vue';
import { UploadOutlined, EyeOutlined, PlayCircleOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import * as ExcelJS from 'exceljs';
import dayjs from 'dayjs';
import { getEntrustRetractList, countDelClient, delClient, type ClientId } from '../server/api'
import { WithdrawalCaseDB, type WithdrawalCaseRecord } from '../utils/indexedDB'
import { handle401Error } from '../utils/auth'

// 页面标题
document.title = '撤委案管理';

// 表单数据
const formData = reactive({});

// 文件列表
const fileList = ref<any[]>([]);

// 加载状态
const previewLoading = ref(false);
const processLoading = ref(false);
const exportLoading = ref(false);

// 预览相关
const previewVisible = ref(false);
const previewData = ref<any>(null);
const previewActiveKey = ref('0');

// 用户详情相关
const userDetailVisible = ref(false);
const userDetailData = ref<any>(null);
const originalWithdrawalRecord = ref<any>(null); // 保存原始的撤委案记录

// 撤委案确认相关
const withdrawalConfirmVisible = ref(false);
const withdrawalConfirmData = ref<any>(null);
const withdrawalLoading = ref(false);
const currentWithdrawalRecord = ref<any>(null);

// 处理结果
const processedResults = ref<any[]>([]);

// 初始化IndexedDB
const db = new WithdrawalCaseDB();
let dbInitialized = false;

// 初始化数据库
const initDB = async () => {
  if (!dbInitialized) {
    try {
      await db.init();
      dbInitialized = true;
      console.log('IndexedDB初始化成功');
    } catch (error) {
      console.error('IndexedDB初始化失败:', error);
      message.error('数据库初始化失败');
    }
  }
};

// 从IndexedDB加载数据
const loadDataFromDB = async () => {
  try {
    await initDB();

    // 清理超过7天的旧数据
    const deletedCount = await db.cleanupOldData(7);
    if (deletedCount > 0) {
      console.log(`清理了 ${deletedCount} 条超过7天的旧数据`);
    }

    const allRecords = await db.getAllWithdrawalCases();
    console.log('allRecords', allRecords);

    if (allRecords.length > 0) {
      // 先过滤出近7天的数据
      const recentRecords = allRecords.filter(record => isWithinLast7Days(record.updateDate));
      console.log(`总记录数: ${allRecords.length}, 近7天记录数: ${recentRecords.length}`);

      // 按更新日期分组（Excel中的实际日期）
      const recordsByDate = new Map<string, WithdrawalCaseRecord[]>();
      recentRecords.forEach(record => {
        // 使用updateDate进行分组，这是Excel中的实际日期
        const parsedDate = parseDate(record.updateDate);
        const dateKey = parsedDate ? parsedDate.format('YYYY-MM-DD') : 'unknown';
        console.log(`记录分组: ${record.name}, updateDate: ${record.updateDate}, dateKey: ${dateKey}`);
        if (!recordsByDate.has(dateKey)) {
          recordsByDate.set(dateKey, []);
        }
        recordsByDate.get(dateKey)!.push(record);
      });

      console.log('按日期分组结果:', Array.from(recordsByDate.entries()));

      // 重建processedResults结构，按日期分组
      const results: any[] = [];
      const sortedDates = Array.from(recordsByDate.keys()).sort((a, b) => b.localeCompare(a)); // 按日期倒序

      sortedDates.forEach(dateKey => {
        const dateRecords = recordsByDate.get(dateKey)!;

        // 按文件名和工作表分组
        const recordsByFileAndSheet = new Map<string, WithdrawalCaseRecord[]>();
        dateRecords.forEach(record => {
          const key = `${record.fileName}_${record.sheetName}`;
          if (!recordsByFileAndSheet.has(key)) {
            recordsByFileAndSheet.set(key, []);
          }
          recordsByFileAndSheet.get(key)!.push(record);
        });

        // 为每个文件和工作表组合创建结果
        recordsByFileAndSheet.forEach((sheetRecords, key) => {
          const [fileName, sheetName] = key.split('_', 2);
          const todayData = sheetRecords.map(record => ({
            ...record,
            key: record.id
          }));

          results.push({
            fileName,
            sheetName,
            dateKey,
            todayData,
            totalData: sheetRecords
          });
        });
      });

      processedResults.value = results;
      console.log(`从IndexedDB加载了 ${allRecords.length} 条记录，按 ${sortedDates.length} 个日期分组`);

      // 保留/恢复激活的tab：优先使用本地缓存，其次使用上一次值，否则选第一个
      const prevActive = activeTabKey.value;
      const storedActive = localStorage.getItem(ACTIVE_TAB_STORAGE_KEY) || '';
      const candidate = storedActive || prevActive;
      if (candidate && sortedDates.includes(candidate)) {
        activeTabKey.value = candidate;
      } else if (sortedDates.length > 0) {
        activeTabKey.value = sortedDates[0];
      }
    }
  } catch (error) {
    console.error('从IndexedDB加载数据失败:', error);
  }
};

// 根据四个关键字段查找记录
const findRecordByKeyFields = async (organization: string, name: string, idCard: string, phone: string): Promise<WithdrawalCaseRecord | null> => {
  try {
    await initDB();
    const allRecords = await db.getAllWithdrawalCases();

    console.log(`🔍 在 ${allRecords.length} 条记录中查找匹配记录`);
    console.log(`🔍 查找条件:`, { organization, name, idCard, phone });

    const foundRecord = allRecords.find(record => {
      // 更宽松的匹配条件，允许部分字段为空或undefined
      const isMatch = (record.organization === organization || (!record.organization && !organization)) &&
        (record.name === name || (!record.name && !name)) &&
        (record.idCard === idCard || (!record.idCard && !idCard)) &&
        (record.phone === phone || (!record.phone && !phone));

      if (isMatch) {
        console.log(`✅ 找到匹配记录:`, record);
      } else {
        // 显示不匹配的详细信息
        console.log(`❌ 记录不匹配:`, {
          record: {
            organization: record.organization,
            name: record.name,
            idCard: record.idCard,
            phone: record.phone
          },
          search: {
            organization,
            name,
            idCard,
            phone
          },
          match: {
            organization: record.organization === organization,
            name: record.name === name,
            idCard: record.idCard === idCard,
            phone: record.phone === phone
          }
        });
      }

      return isMatch;
    });

    if (!foundRecord) {
      console.log(`❌ 未找到匹配记录，显示前几条记录供参考:`);
      allRecords.slice(0, 3).forEach((record, index) => {
        console.log(`   记录${index + 1}:`, {
          organization: record.organization,
          name: record.name,
          idCard: record.idCard,
          phone: record.phone
        });
      });
    }

    return foundRecord || null;
  } catch (error) {
    console.error('查找记录失败:', error);
    return null;
  }
};

// 页面加载时恢复数据
loadDataFromDB();





// 整合所有今天的数据
const allTodayData = computed(() => {
  const mergedData: any[] = [];
  processedResults.value.forEach(result => {
    result.todayData.forEach((item: any) => {
      mergedData.push({
        ...item,
        sheetName: result.sheetName,
        fileName: result.fileName,
        status: item.status || 0 // 从IndexedDB获取状态，默认为0
      });
    });
  });
  return mergedData;
});

// 按日期分组的数据
const dateGroups = computed(() => {
  const groups = new Map<string, any[]>();

  processedResults.value.forEach(result => {
    const dateKey = result.dateKey || dayjs().format('YYYY-MM-DD');
    if (!groups.has(dateKey)) {
      groups.set(dateKey, []);
    }

    result.todayData.forEach((item: any) => {
      groups.get(dateKey)!.push({
        ...item,
        sheetName: result.sheetName,
        fileName: result.fileName,
        status: item.status || 0
      });
    });
  });

  // 转换为数组并按日期排序
  return Array.from(groups.entries())
    .map(([dateKey, data]) => ({
      dateKey,
      tabTitle: `${dateKey} (${data.length}条)`,
      data
    }))
    .sort((a, b) => b.dateKey.localeCompare(a.dateKey));
});

// 当前激活的tab + 本地存储key
const ACTIVE_TAB_STORAGE_KEY = 'withdrawal-case-active-date-tab';
const activeTabKey = ref<string>(localStorage.getItem(ACTIVE_TAB_STORAGE_KEY) || '');

// 监听tab变更，写入本地存储
watch(activeTabKey, (val) => {
  if (val) {
    localStorage.setItem(ACTIVE_TAB_STORAGE_KEY, val);
  }
});

// 获取机构名称过滤选项（显示 文件名-表名 组合）
const organizationFilters = computed(() => {
  const uniqueCombos = [...new Set(allTodayData.value.map((item: any) => `${item.fileName}-${item.sheetName}`))];
  return uniqueCombos.map(text => ({
    text,
    value: text
  }));
});

// 表格列定义
const tableColumns = computed(() => [
  {
    title: '机构名称',
    dataIndex: 'sheetName',
    key: 'sheetName',
    width: 200,
    filters: organizationFilters.value,
    onFilter: (value: string, record: any) => `${record.fileName}-${record.sheetName}` === value,
    filterSearch: true,
    customRender: ({ record }: { record: any }) => `${record.fileName}-${record.sheetName}`
  },
  {
    title: '当事人信息',
    key: 'personInfo',
    width: 200,
    customRender: ({ record }: { record: any }) => {
      return h('div', { style: 'text-align: left; line-height: 1.4;' }, [
        h('div', { style: 'font-weight: 500; margin-bottom: 2px;' }, record.name || '-'),
        h('div', { style: 'font-size: 12px; color: #666; margin-bottom: 2px;' }, `身份证尾号: ${record.idCard || '-'}`),
        h('div', { style: 'font-size: 12px; color: #666;' }, `手机号码: ${record.phone || '-'}`)
      ]);
    }
  },
  { title: '撤案原由', dataIndex: 'reason', key: 'reason', width: 150 },
  { title: '更新日期', dataIndex: 'updateDate', key: 'updateDate', width: 120 },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 150 },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }: { record: any }) => {
      return record.status === 1 ?
        h('a-tag', { color: 'green' }, '已撤案') :
        h('a-tag', { color: 'orange' }, '未撤案');
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
    fixed: 'right'
  }
]);

const previewColumns = [
  { title: '机构', dataIndex: 'organization', key: 'organization', width: 120 },
  { title: '当事人姓名', dataIndex: 'name', key: 'name', width: 120 },
  { title: '身份证后六位', dataIndex: 'idCard', key: 'idCard', width: 120 },
  { title: '撤案原由', dataIndex: 'reason', key: 'reason', width: 150 },
  { title: '当事人手机号前三后四', dataIndex: 'phone', key: 'phone', width: 180 },
  { title: '更新日期', dataIndex: 'updateDate', key: 'updateDate', width: 120 },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 150 }
];

// 文件上传前处理
const beforeUpload = (file: any) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    message.error('只能上传Excel文件!');
    return false;
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!');
    return false;
  }
  return false; // 阻止自动上传
};

// 移除文件
const handleRemove = (file: any) => {
  const index = fileList.value.findIndex(item => item.uid === file.uid);
  if (index > -1) {
    fileList.value.splice(index, 1);
  }
};

// 定义数据类型
interface RowData {
  organization: string;
  name: string;
  idCard: string;
  reason: string;
  phone: string;
  updateDate: string;
  remark: string;
}

interface SheetData {
  name: string;
  data: RowData[];
}

interface ExcelFileData {
  fileName: string;
  sheets: SheetData[];
}




// 解析Excel文件
const parseExcelFile = async (file: File): Promise<ExcelFileData> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const data = e.target?.result;
        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(data as ArrayBuffer);

        const sheets: SheetData[] = [];
        workbook.eachSheet((worksheet) => {
          const sheetData: RowData[] = [];
          const sheetName = worksheet.name;

          // 跳过空工作表
          if (worksheet.rowCount === 0) return;

          worksheet.eachRow((row, rowNumber) => {
            if (rowNumber === 1) return; // 跳过表头

            // 获取日期单元格的原始值
            const dateCell = row.getCell(6);
            let dateValue = '';

            // 检查单元格类型
            if (dateCell.type === ExcelJS.ValueType.Date) {
              // 如果是日期类型，获取原始值
              const cellValue = dateCell.value;
              if (cellValue instanceof Date) {
                // 将Date对象转换为字符串格式
                const year = cellValue.getFullYear();
                const month = cellValue.getMonth() + 1;
                const day = cellValue.getDate();
                dateValue = `${year}/${month}/${day}`;
                console.log(`日期单元格(Date类型): ${cellValue} -> ${dateValue}`);
              } else {
                dateValue = cellValue?.toString() || '';
                console.log(`日期单元格(其他类型): ${dateValue}`);
              }
            } else if (dateCell.type === ExcelJS.ValueType.Number) {
              // 如果是数字类型，先检查是否是8位日期格式
              const excelSerialDate = dateCell.value as number;
              console.log(`Excel数字单元格: ${excelSerialDate}`);

              if (excelSerialDate && typeof excelSerialDate === 'number') {
                // 检查是否是8位日期格式（如20251022）
                const dateStr = excelSerialDate.toString();
                if (/^\d{8}$/.test(dateStr)) {
                  // 直接使用8位数字作为日期字符串
                  dateValue = dateStr;
                  console.log(`8位数字日期格式: ${excelSerialDate} -> ${dateValue}`);
                } else {
                  // 否则按Excel日期序列号处理
                  const jsDate = new Date((excelSerialDate - 25569) * 86400 * 1000);
                  console.log(`转换后的日期: ${jsDate}`);

                  if (!isNaN(jsDate.getTime())) {
                    const year = jsDate.getFullYear();
                    const month = jsDate.getMonth() + 1;
                    const day = jsDate.getDate();
                    dateValue = `${year}/${month}/${day}`;
                    console.log(`Excel日期序列号: ${excelSerialDate} -> ${dateValue}`);
                  } else {
                    dateValue = excelSerialDate.toString();
                    console.log(`数字日期解析失败: ${excelSerialDate}`);
                  }
                }
              } else {
                dateValue = excelSerialDate?.toString() || '';
                console.log(`数字日期解析失败: ${excelSerialDate}`);
              }
            } else {
              // 如果不是日期类型，直接获取文本
              dateValue = dateCell.text || '';
              console.log(`日期单元格(文本类型): ${dateValue}`);
            }

            console.log(`原始行数据:`, {
              机构: row.getCell(1).text || '',
              当事人姓名: row.getCell(2).text || '',
              身份证后六位: row.getCell(3).text || '',
              撤案原由: row.getCell(4).text || '',
              当事人手机号前三后四: row.getCell(5).text || '',
              更新日期原始值: dateValue,
              更新日期格式化后: formatDate(dateValue),
              备注: row.getCell(7).text || ''
            });

            const rowData: RowData = {
              organization: row.getCell(1).text || '',
              name: row.getCell(2).text || '',
              idCard: row.getCell(3).text || '',
              reason: row.getCell(4).text || '',
              phone: row.getCell(5).text || '',
              updateDate: formatDate(dateValue),
              remark: row.getCell(7).text || ''
            };

            // 只添加非空行
            if (rowData.organization || rowData.name || rowData.idCard) {
              sheetData.push(rowData);
            }
          });

          if (sheetData.length > 0) {
            sheets.push({
              name: sheetName,
              data: sheetData
            });
          }
        });

        resolve({
          fileName: file.name,
          sheets
        });
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
};

// 预览Excel
const previewExcel = async () => {
  if (fileList.value.length === 0) {
    message.warning('请先选择Excel文件');
    return;
  }

  previewLoading.value = true;
  try {
    const allSheets = [];

    for (const fileItem of fileList.value) {
      const file = fileItem.originFileObj || fileItem;
      const result = await parseExcelFile(file);
      allSheets.push(...(result as any).sheets);
    }

    previewData.value = {
      sheets: allSheets
    };
    previewVisible.value = true;
    previewActiveKey.value = '0';
  } catch (error) {
    console.error('解析Excel失败:', error);
    message.error('解析Excel文件失败，请检查文件格式');
  } finally {
    previewLoading.value = false;
  }
};

// 处理Excel
const processExcel = async () => {
  if (fileList.value.length === 0) {
    message.warning('请先选择Excel文件');
    return;
  }

  // 确保数据库已初始化
  await initDB();

  processLoading.value = true;
  try {
    const results = [];
    const allRecords: WithdrawalCaseRecord[] = [];
    const allExistingRecords: WithdrawalCaseRecord[] = [];

    for (const fileItem of fileList.value) {
      const file = fileItem.originFileObj || fileItem;
      const result = await parseExcelFile(file);
      const fileData = result as any;

      // 检查数据库中是否已存在该文件的数据
      const existingRecords = await db.getWithdrawalCasesByFileName(fileData.fileName);
      allExistingRecords.push(...existingRecords);

      // 处理每个工作表
      for (const sheet of fileData.sheets) {
        const todayData = [];
        const totalData = sheet.data;

        // 筛选今天的数据
        console.log(`\n=== 处理工作表: ${sheet.name} ===`);
        console.log(`总数据行数: ${sheet.data.length}`);

        for (const row of sheet.data) {
          console.log(`原始行数据:`, {
            机构: row.organization,
            当事人姓名: row.name,
            身份证后六位: row.idCard,
            撤案原由: row.reason,
            当事人手机号前三后四: row.phone,
            更新日期: row.updateDate,
            备注: row.remark
          });

          if (isWithinLast7Days(row.updateDate)) {
            // 根据备注判断Excel中的撤案状态：备注不为空表示已撤案
            const excelIsWithdrawn = row.remark && row.remark.trim() !== '';
            const excelStatus = excelIsWithdrawn ? 1 : 0;

            // 使用关键字段组合来查找匹配的记录：机构、当事人姓名、身份证后六位、当事人手机号前三后四
            const existingRecord = allExistingRecords.find(existing =>
              existing.organization === row.organization &&
              existing.name === row.name &&
              existing.idCard === row.idCard &&
              existing.phone === row.phone
            );

            if (existingRecord) {
              // 如果找到匹配记录，进行状态合并逻辑
              const dbStatus = existingRecord.status;

              // 状态合并规则：
              // 1. 如果Excel和数据库都是待撤委案(0)，则状态为待撤委案(0)
              // 2. 如果Excel或数据库中有一方是已撤委案(1)，则状态为已撤委案(1)
              const mergedStatus = (excelStatus === 1 || dbStatus === 1) ? 1 : 0;

              // 更新现有记录
              const updatedRecord: WithdrawalCaseRecord = {
                ...existingRecord, // 保持原有信息
                fileName: fileData.fileName, // 更新文件名
                sheetName: sheet.name, // 更新工作表名
                reason: row.reason, // 更新撤案原由
                updateDate: row.updateDate, // 更新更新日期
                remark: row.remark, // 更新备注
                status: mergedStatus, // 使用合并后的状态
                updatedAt: Date.now() // 更新修改时间
              };

              console.log(`📝 更新匹配记录: ${updatedRecord.name}`);
              console.log(`   匹配条件: 机构=${row.organization}, 姓名=${row.name}, 身份证=${row.idCard}, 手机=${row.phone}`);
              console.log(`   Excel状态: ${excelStatus === 1 ? '已撤委案' : '待撤委案'} (备注: ${row.remark || '无'})`);
              console.log(`   数据库状态: ${dbStatus === 1 ? '已撤委案' : '待撤委案'}`);
              console.log(`   合并后状态: ${mergedStatus === 1 ? '已撤委案' : '待撤委案'}`);

              allRecords.push(updatedRecord);
            } else {
              // 如果没有找到匹配记录，创建新记录
              const uniqueKey = `${fileData.fileName}_${sheet.name}_${row.name}_${row.idCard}_${Date.now()}`;

              const newRecord: WithdrawalCaseRecord = {
                id: uniqueKey,
                fileName: fileData.fileName,
                sheetName: sheet.name,
                organization: row.organization,
                name: row.name,
                idCard: row.idCard,
                reason: row.reason,
                phone: row.phone,
                updateDate: row.updateDate,
                remark: row.remark,
                status: excelStatus, // 使用Excel中的状态
                createdAt: Date.now(),
                updatedAt: Date.now()
              };

              console.log(`➕ 新增记录: ${newRecord.name}, Excel状态: ${excelStatus === 1 ? '已撤委案' : '待撤委案'} (备注: ${row.remark || '无'})`);

              allRecords.push(newRecord);
            }

            // 为显示创建todayRow（使用最后处理的记录）
            const lastRecord = allRecords[allRecords.length - 1];
            const todayRow = {
              ...lastRecord,
              key: lastRecord.id
            };
            todayData.push(todayRow);
            console.log(`✅ 今日数据:`, todayRow);
          } else {
            console.log(`❌ 非今日数据: ${row.updateDate}`);
          }
        }

        console.log(`今日数据条数: ${todayData.length}`);

        results.push({
          fileName: fileData.fileName,
          sheetName: sheet.name,
          todayData,
          totalData
        });
      }

      // 保存Excel文件记录
      await db.addExcelFile({
        id: fileData.fileName,
        fileName: fileData.fileName,
        fileSize: file.size || 0,
        uploadTime: Date.now(),
        processedTime: Date.now(),
        totalRecords: allRecords.filter(record => record.fileName === fileData.fileName).length,
        todayRecords: allRecords.filter(record => record.fileName === fileData.fileName).length
      });
    }

    // 批量保存到IndexedDB
    await db.upsertWithdrawalCases(allRecords);

    // 统计处理结果
    const newRecords = allRecords.filter(record => record.createdAt === record.updatedAt);
    const updatedRecords = allRecords.filter(record => record.createdAt !== record.updatedAt);
    const withdrawnRecords = allRecords.filter(record => record.status === 1);
    const pendingRecords = allRecords.filter(record => record.status === 0);

    console.log(`📊 处理统计:`);
    console.log(`   新增记录: ${newRecords.length} 条`);
    console.log(`   更新记录: ${updatedRecords.length} 条`);
    console.log(`   已撤委案记录: ${withdrawnRecords.length} 条`);
    console.log(`   待撤委案记录: ${pendingRecords.length} 条`);

    // 重新从数据库加载数据以正确显示tab
    await loadDataFromDB();

    message.success(`处理完成！共处理 ${results.length} 个工作表，近7天数据 ${allTodayData.value.length} 条（新增${newRecords.length}条，更新${updatedRecords.length}条）`);
  } catch (error) {
    console.error('处理Excel失败:', error);
    message.error('处理Excel文件失败，请检查文件格式');
  } finally {
    processLoading.value = false;
  }
};

// 格式化日期为 2025.9.17 格式
const formatDate = (dateStr: string): string => {
  if (!dateStr) return '';

  let parsedDate: dayjs.Dayjs | undefined;
  const originalDateStr = dateStr;
  console.log(`原始日期: ${originalDateStr}`);

  // 处理不同的日期格式
  if (dateStr.includes('年') && dateStr.includes('月') && dateStr.includes('日')) {
    // 处理 2025年9月18日 格式
    const match = dateStr.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
    if (match) {
      const year = parseInt(match[1]);
      const month = parseInt(match[2]);
      const day = parseInt(match[3]);
      parsedDate = dayjs(new Date(year, month - 1, day));
      console.log(`中文日期格式: ${originalDateStr} -> ${parsedDate.format('YYYY.M.D')}`);
    }
  } else if (/^\d{8}$/.test(dateStr)) {
    // 处理 20251022 格式（8位纯数字）
    const year = parseInt(dateStr.substring(0, 4));
    const month = parseInt(dateStr.substring(4, 6));
    const day = parseInt(dateStr.substring(6, 8));
    parsedDate = dayjs(new Date(year, month - 1, day));
    console.log(`8位数字日期格式: ${originalDateStr} -> ${parsedDate.format('YYYY.M.D')}`);
  } else if (dateStr.includes('.')) {
    // 处理 2025.9.17 或 2025.09.17 格式
    const parts = dateStr.split('.');
    if (parts.length === 3) {
      const year = parseInt(parts[0]);
      const month = parseInt(parts[1]);
      const day = parseInt(parts[2]);
      parsedDate = dayjs(new Date(year, month - 1, day));
      console.log(`点号日期格式: ${originalDateStr} -> ${parsedDate.format('YYYY.M.D')}`);
    }
  } else if (dateStr.includes('/')) {
    // 处理 2025/8/28 或 2025/09/18 格式
    const parts = dateStr.split('/');
    if (parts.length === 3) {
      const year = parseInt(parts[0]);
      const month = parseInt(parts[1]);
      const day = parseInt(parts[2]);
      parsedDate = dayjs(new Date(year, month - 1, day));
      console.log(`斜杠日期格式: ${originalDateStr} -> ${parsedDate.format('YYYY.M.D')}`);
    } else {
      parsedDate = dayjs(dateStr, 'YYYY/M/D');
      console.log(`斜杠日期格式(dayjs): ${originalDateStr} -> ${parsedDate.format('YYYY.M.D')}`);
    }
  } else if (dateStr.includes('GMT') || dateStr.includes('中国标准时间')) {
    // 处理 'Wed Sep 17 2025 08:00:00 GMT+0800 (中国标准时间)' 格式
    parsedDate = dayjs(new Date(dateStr));
    console.log(`GMT日期格式: ${originalDateStr} -> ${parsedDate.format('YYYY.M.D')}`);
  } else {
    // 尝试其他格式
    parsedDate = dayjs(dateStr);
    console.log(`其他日期格式: ${originalDateStr} -> ${parsedDate.format('YYYY.M.D')}`);
  }

  if (parsedDate && parsedDate.isValid()) {
    return parsedDate.format('YYYY.M.D');
  }

  console.warn(`日期解析失败: ${originalDateStr}`);
  return dateStr; // 如果解析失败，返回原始字符串
};

// 解析日期字符串为dayjs对象
const parseDate = (dateStr: string): dayjs.Dayjs | null => {
  if (!dateStr) return null;

  let parsedDate: dayjs.Dayjs | undefined;
  if (dateStr.includes('年') && dateStr.includes('月') && dateStr.includes('日')) {
    // 处理 2025年9月18日 格式
    const match = dateStr.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
    if (match) {
      const year = parseInt(match[1]);
      const month = parseInt(match[2]);
      const day = parseInt(match[3]);
      parsedDate = dayjs(new Date(year, month - 1, day));
    }
  } else if (/^\d{8}$/.test(dateStr)) {
    // 处理 20251022 格式（8位纯数字）
    const year = parseInt(dateStr.substring(0, 4));
    const month = parseInt(dateStr.substring(4, 6));
    const day = parseInt(dateStr.substring(6, 8));
    parsedDate = dayjs(new Date(year, month - 1, day));
  } else if (dateStr.includes('.')) {
    // 处理 2025.9.17 或 2025.09.17 格式
    const parts = dateStr.split('.');
    if (parts.length === 3) {
      const year = parseInt(parts[0]);
      const month = parseInt(parts[1]);
      const day = parseInt(parts[2]);
      parsedDate = dayjs(new Date(year, month - 1, day));
    }
  } else if (dateStr.includes('/')) {
    // 处理 2025/8/28 或 2025/09/18 格式
    const parts = dateStr.split('/');
    if (parts.length === 3) {
      const year = parseInt(parts[0]);
      const month = parseInt(parts[1]);
      const day = parseInt(parts[2]);
      parsedDate = dayjs(new Date(year, month - 1, day));
    } else {
      parsedDate = dayjs(dateStr, 'YYYY/M/D');
    }
  } else if (dateStr.includes('GMT') || dateStr.includes('中国标准时间')) {
    // 处理 'Wed Sep 17 2025 08:00:00 GMT+0800 (中国标准时间)' 格式
    parsedDate = dayjs(new Date(dateStr));
  } else {
    // 尝试其他格式
    parsedDate = dayjs(dateStr);
  }

  return parsedDate && parsedDate.isValid() ? parsedDate : null;
};

// 判断是否为今天
const isToday = (dateStr: string): boolean => {
  const parsedDate = parseDate(dateStr);
  const today = dayjs();
  const isTodayResult = parsedDate ? parsedDate.isSame(today, 'day') : false;

  console.log(`isToday检查: ${dateStr} -> 是今天: ${isTodayResult}`);
  return isTodayResult;
};

// 判断是否为近7天的数据
const isWithinLast7Days = (dateStr: string): boolean => {
  const parsedDate = parseDate(dateStr);
  if (!parsedDate) return false;

  const today = dayjs();
  const sevenDaysAgo = today.subtract(7, 'day');
  const isWithinRange = parsedDate.isAfter(sevenDaysAgo) && (parsedDate.isSame(today) || parsedDate.isBefore(today));

  console.log(`近7天检查: ${dateStr} -> 在范围内: ${isWithinRange}`);
  return isWithinRange;
};

// 导出Excel功能
const exportToExcel = async () => {
  if (dateGroups.value.length === 0) {
    message.warning('没有数据可导出');
    return;
  }

  exportLoading.value = true;
  try {
    const workbook = new ExcelJS.Workbook();

    // 设置列标题
    const headers = [
      '机构名称',
      '当事人姓名',
      '身份证后六位',
      '撤案原由',
      '当事人手机号前三后四',
      '更新日期',
      '备注'
    ];

    // 为每个日期分组创建一个工作表
    dateGroups.value.forEach((dateGroup) => {
      const worksheet = workbook.addWorksheet(dateGroup.dateKey);

      console.log(`📊 创建工作表: ${dateGroup.dateKey}, 数据条数: ${dateGroup.data.length}`);

      // 添加表头
      worksheet.addRow(headers);

      // 设置表头样式
      const headerRow = worksheet.getRow(1);
      headerRow.height = 25;
      headerRow.eachCell((cell) => {
        cell.font = { bold: true, size: 12 };
        cell.alignment = { horizontal: 'center', vertical: 'middle' };
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFE6F7FF' }
        };
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        };
      });

      // 添加数据行
      dateGroup.data.forEach((item: any) => {
        const row = worksheet.addRow([
          item.sheetName,
          item.name,
          item.idCard,
          item.reason,
          item.phone,
          item.updateDate,
          item.remark
        ]);

        // 设置数据行样式
        row.height = 22;
        row.eachCell((cell) => {
          cell.alignment = { horizontal: 'center', vertical: 'middle' };
          cell.border = {
            top: { style: 'thin' },
            left: { style: 'thin' },
            bottom: { style: 'thin' },
            right: { style: 'thin' }
          };

          // 根据状态设置背景色
          if (item.status === 1) {
            // 已撤委案 - 绿色背景
            cell.fill = {
              type: 'pattern',
              pattern: 'solid',
              fgColor: { argb: 'FFE6FFE6' }
            };
          } else if (isToday(item.updateDate)) {
            // 今日数据 - 浅蓝色背景
            cell.fill = {
              type: 'pattern',
              pattern: 'solid',
              fgColor: { argb: 'FFF0F8FF' }
            };
          }
        });
      });

      // 设置列宽
      worksheet.columns = [
        { width: 15 }, // 机构名称
        { width: 12 }, // 当事人姓名
        { width: 15 }, // 身份证后六位
        { width: 20 }, // 撤案原由
        { width: 25 }, // 当事人手机号前三后四
        { width: 12 }, // 更新日期
        { width: 20 }  // 备注
      ];
    });

    // 生成Excel文件
    const buffer = await workbook.xlsx.writeBuffer();

    // 创建下载链接
    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;

    // 生成文件名
    const today = dayjs().format('YYYY-MM-DD');
    const fileName = `撤委案数据_按日期分组_${today}.xlsx`;
    link.download = fileName;

    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    message.success(`Excel文件已导出：${fileName}，共${dateGroups.value.length}个工作表`);
  } catch (error) {
    console.error('导出Excel失败:', error);
    message.error('导出Excel失败，请重试');
  } finally {
    exportLoading.value = false;
  }
};

// 处理用户详情操作
const handleUserDetail = async (record: any) => {
  try {
    // 设置该行的加载状态
    record.detailLoading = true;

    // 根据机构名称获取customerId
    const customerId = '1322068017848881154';

    // 构建API请求参数
    const requestParams = {
      current: 1,
      size: 20,
      queryType: "entrust",
      key: record.name, // 当事人姓名
      channelFrom: "",
      overdueDayStart: "",
      overdueDayEnd: "",
      productTypeCodes: [],
      states: [],
      disStates: ["ENTRUST_END"],
      staffIds: [],
      bizLevel: "",
      batchIds: [],
      riskType: "",
      riskIdentification: "",
      entrustCustomerIds: [customerId], // 根据机构名称获取的customerId
      lastBackedDateStart: null,
      lastBackedDateEnd: null,
      loanCreatedStart: null,
      loanCreatedEnd: null,
      tsToken: "7bc197bc91c6435c8b1ce78d32b24d1a"
    };

    // 调用API获取用户数据
    const response = await getEntrustRetractList(requestParams);

    if (response.success && response.result && response.result.records && response.result.records.length > 0) {
      // 找到用户数据
      const userData = response.result.records[0]; // 取第一条记录

      console.log('🔍 API返回的用户数据:', userData);
      console.log('🔍 用户数据中的关键字段:', {
        channelFrom: userData.channelFrom,
        clientId: userData.clientId,
        channelId: userData.channelId,
        allKeys: Object.keys(userData)
      });

      userDetailData.value = {
        ...userData,
        // 保留撤委案记录中的关键信息
        sheetName: record.sheetName,
        organization: record.organization,
        channelFrom: userData.channelFrom || userData.channelId, // 使用API返回的channelFrom
        clientId: userData.clientId, // 使用API返回的clientId
        records: response.result.records
      };

      console.log('🔍 构建的userDetailData:', userDetailData.value);

      // 保存原始的撤委案记录，用于后续更新数据库
      originalWithdrawalRecord.value = record;
      userDetailVisible.value = true;
    } else {
      // 未找到用户数据
      console.log('⚠️ 未找到用户数据，使用撤委案记录数据');
      userDetailData.value = {
        name: record.name,
        sheetName: record.sheetName,
        organization: record.organization,
        channelFrom: record.channelFrom || record.channelId, // 使用撤委案记录中的channelFrom
        clientId: record.clientId, // 使用撤委案记录中的clientId
        records: []
      };
      // 保存原始的撤委案记录，用于后续更新数据库
      originalWithdrawalRecord.value = record;
      userDetailVisible.value = true;
    }

  } catch (error) {
    console.error('获取用户详情失败:', error);
    message.error('获取用户详情失败，请重试');
  } finally {
    record.detailLoading = false;
  }
};

// 获取性别文本
const getGenderText = (gender: string) => {
  const genderMap: { [key: string]: string } = {
    'MALE': '男',
    'FEMALE': '女',
    'UNKNOWN': '未知'
  };
  return genderMap[gender] || '-';
};

// 格式化金额
const formatMoney = (amount: number) => {
  if (amount === null || amount === undefined) return '-';
  return `¥${amount.toFixed(2)}`;
};

// 格式化时间
const formatTime = (timestamp: number) => {
  if (!timestamp) return '-';
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
};

// 获取委案状态颜色
const getDistributeStateColor = (code: string) => {
  const colorMap: { [key: string]: string } = {
    'ENTRUST_END': 'red',
    'ENTRUST_START': 'blue',
    'ENTRUST_PROCESSING': 'orange',
    'ENTRUST_PENDING': 'yellow'
  };
  return colorMap[code] || 'default';
};

// 获取贷款状态颜色
const getLoanStateColor = (code: string) => {
  const colorMap: { [key: string]: string } = {
    'OVERDUE': 'red',
    'NORMAL': 'green',
    'PAID': 'blue',
    'CANCELLED': 'gray'
  };
  return colorMap[code] || 'default';
};

// 处理撤委案操作
const handleWithdrawal = async (record: any) => {
  try {
    withdrawalLoading.value = true;
    // 使用保存的原始撤委案记录，而不是API返回的用户数据
    currentWithdrawalRecord.value = originalWithdrawalRecord.value || record;

    // 构建clientIds参数
    // record是userDetailData，包含API返回的用户信息
    console.log('🔍 handleWithdrawal - 构建clientIds参数:', {
      record: record,
      currentWithdrawalRecord: currentWithdrawalRecord.value,
      channelFrom: record.channelFrom,
      channelId: record.channelId,
      clientId: record.clientId
    });

    const channelId = record.channelFrom || record.channelId;
    const clientId = record.clientId;

    if (!channelId || !clientId) {
      console.error('❌ handleWithdrawal - clientIds参数构建失败:', {
        channelId,
        clientId,
        channelFrom: record.channelFrom,
        channelIdField: record.channelId,
        recordKeys: Object.keys(record)
      });
      message.error('缺少必要的客户信息，无法执行撤委案操作。请确保用户详情数据包含channelFrom和clientId字段。');
      return;
    }

    const clientIds: ClientId[] = [{
      channelId,
      clientId
    }];

    console.log('✅ handleWithdrawal - 构建的clientIds参数:', clientIds);

    // 调用初始化撤委案接口
    const initParams = {
      clientIds,
      tsToken: "a3a8d225f22e4a64a47c7c963bd66552"
    };

    const response = await countDelClient(initParams);

    if (response.success && response.result) {
      // 显示撤委案确认弹框
      withdrawalConfirmData.value = response.result;
      withdrawalConfirmVisible.value = true;
    } else {
      message.error('初始化撤委案失败，请重试');
    }

  } catch (error: any) {
    console.error('初始化撤委案失败:', error);

    // 检查是否是401错误
    if (error.response?.status === 401 || error.message === '未授权') {
      handle401Error();
      return;
    }

    message.error('初始化撤委案失败，请重试');
  } finally {
    withdrawalLoading.value = false;
  }
};

// 确认撤委案操作
const confirmWithdrawal = async () => {
  try {
    withdrawalLoading.value = true;

    if (!currentWithdrawalRecord.value) {
      message.error('未找到撤委案记录');
      return;
    }

    if (!userDetailData.value) {
      message.error('未找到用户详情数据，请重新获取用户详情');
      return;
    }

    // 构建clientIds参数
    // 注意：currentWithdrawalRecord.value是撤委案记录，不包含channelFrom和clientId
    // 这些字段在userDetailData中，需要从userDetailData获取
    console.log('🔍 confirmWithdrawal - 构建clientIds参数前的记录信息:', {
      currentWithdrawalRecord: currentWithdrawalRecord.value,
      userDetailData: userDetailData.value,
      channelFrom: userDetailData.value?.channelFrom,
      channelId: userDetailData.value?.channelId,
      clientId: userDetailData.value?.clientId
    });

    // 从userDetailData获取channelFrom和clientId
    const channelId = userDetailData.value?.channelFrom || userDetailData.value?.channelId;
    const clientId = userDetailData.value?.clientId;

    if (!channelId || !clientId) {
      console.error('❌ confirmWithdrawal - clientIds参数构建失败:', {
        channelId,
        clientId,
        userDetailData: userDetailData.value,
        userDetailDataKeys: userDetailData.value ? Object.keys(userDetailData.value) : 'userDetailData is null',
        currentWithdrawalRecord: currentWithdrawalRecord.value,
        currentWithdrawalRecordKeys: currentWithdrawalRecord.value ? Object.keys(currentWithdrawalRecord.value) : 'currentWithdrawalRecord is null'
      });
      message.error('缺少必要的客户信息，无法执行撤委案操作。请确保用户详情数据包含channelFrom和clientId字段。');
      return;
    }

    const clientIds: ClientId[] = [{
      channelId,
      clientId
    }];

    console.log('✅ 构建的clientIds参数:', clientIds);

    // 调用撤委案提交接口
    const submitParams = {
      clientIds,
      tsToken: "a3a8d225f22e4a64a47c7c963bd66552"
    };

    const response = await delClient(submitParams);

    if (response.success) {
      message.success(response.result?.message || '撤委案操作成功');

      // 更新记录状态
      currentWithdrawalRecord.value.status = 1;
      currentWithdrawalRecord.value.withdrawalTime = dayjs().format('YYYY-MM-DD HH:mm:ss');

      // 更新IndexedDB中的记录状态
      // 使用四个关键字段来查找并更新记录
      console.log(`🔍 查找记录进行状态更新:`, {
        organization: currentWithdrawalRecord.value.organization,
        name: currentWithdrawalRecord.value.name,
        idCard: currentWithdrawalRecord.value.idCard,
        phone: currentWithdrawalRecord.value.phone
      });

      // 显示完整的currentWithdrawalRecord用于调试
      console.log(`🔍 完整的currentWithdrawalRecord:`, currentWithdrawalRecord.value);

      const recordToUpdate = await findRecordByKeyFields(
        currentWithdrawalRecord.value.organization,
        currentWithdrawalRecord.value.name,
        currentWithdrawalRecord.value.idCard,
        currentWithdrawalRecord.value.phone
      );

      if (recordToUpdate) {
        console.log(`📝 找到匹配记录:`, recordToUpdate);
        console.log(`🔄 准备更新记录ID: ${recordToUpdate.id}, 状态: 1`);

        try {
          await db.updateWithdrawalCaseStatus(
            recordToUpdate.id,
            1,
            dayjs().format('YYYY-MM-DD HH:mm:ss'),
            '√' // 撤委案成功后设置备注为'√'
          );
          console.log(`✅ 数据库更新成功: ${currentWithdrawalRecord.value.name}，状态: 已撤委案，备注: √`);

          // 验证更新是否成功
          const updatedRecord = await db.getWithdrawalCaseById(recordToUpdate.id);
          console.log(`🔍 验证更新后的记录:`, updatedRecord);
        } catch (updateError) {
          console.error(`❌ 数据库更新失败:`, updateError);
          message.error('更新数据库记录失败');
        }
      } else {
        console.warn(`⚠️ 未找到匹配的记录进行状态更新: ${currentWithdrawalRecord.value.name}`);
        console.log(`🔍 当前记录信息:`, currentWithdrawalRecord.value);

        // 显示所有记录供调试
        const allRecords = await db.getAllWithdrawalCases();
        console.log(`🔍 数据库中的所有记录 (${allRecords.length}条):`, allRecords);
      }

      // 关闭所有弹框
      withdrawalConfirmVisible.value = false;
      userDetailVisible.value = false;

      // 重新加载数据以刷新列表
      await loadDataFromDB();

      // 显示成功信息
      message.success('撤委案操作成功，数据已更新');

    } else {
      message.error('撤委案操作失败，请重试');
    }

  } catch (error: any) {
    console.error('撤委案操作失败:', error);

    // 检查是否是401错误
    if (error.response?.status === 401 || error.message === '未授权') {
      handle401Error();
      return;
    }

    message.error('撤委案操作失败，请重试');
  } finally {
    withdrawalLoading.value = false;
  }
};
</script>

<style scoped>
.withdrawal-case-container {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.page-description {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.page-content {
  margin-top: 24px;
}

/* 左右布局容器 */
.layout-container {
  display: flex;
  gap: 24px;
}

/* 左侧面板 - 3/10 */
.left-panel {
  flex: 0 0 20%;
  max-width: 20%;
  display: flex;
  flex-direction: column;
}

/* 右侧面板 - 7/10 */
.right-panel {
  flex: 0 0 80%;
  max-width: 80%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding-right: 30px;
}

/* 左侧上传卡片 */
.left-panel .upload-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.left-panel .upload-card :deep(.ant-card-body) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.left-panel .ant-form {
  display: flex;
  flex-direction: column;
}


/* 右侧结果卡片 */
.right-panel .result-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right-panel .result-card :deep(.ant-card-body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.result-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px;
}

.result-summary {
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .layout-container {
    flex-direction: column;
    height: auto;
  }

  .left-panel,
  .right-panel {
    flex: none;
    max-width: 100%;
  }

  .left-panel .upload-card {
    height: auto;
  }

  .right-panel .result-card {
    height: auto;
  }
}

.upload-card {
  background: #fff;
  border-radius: 8px;
}

.result-card {
  background: #fff;
  border-radius: 8px;
}

.upload-tip {
  margin-top: 8px;
  color: #8c8c8c;
  font-size: 12px;
}

/* .result-content 样式已在上面定义 */

.result-summary {
  display: flex;
  gap: 32px;
  margin-bottom: 24px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 6px;
}

.result-summary .ant-statistic {
  text-align: center;
}

.result-summary .ant-statistic-title {
  font-size: 14px;
  color: #666;
}

.result-summary .ant-statistic-content {
  font-size: 20px;
  font-weight: 600;
}

/* 表格单元格垂直水平居中 */
.center-table :deep(.ant-table-thead > tr > th) {
  text-align: center;
  vertical-align: middle;
}

.center-table :deep(.ant-table-tbody > tr > td) {
  text-align: center;
  vertical-align: middle;
}

.center-table :deep(.ant-table-tbody > tr > td .ant-tag) {
  margin: 0;
}

/* 状态列样式 */
.status-withdrawn {
  font-weight: 600;
  border-radius: 4px;
  padding: 2px 8px;
}

.status-pending {
  font-weight: 500;
  border-radius: 4px;
  padding: 2px 8px;
}

/* 操作栏已撤案样式 */
.action-withdrawn {
  color: #d9d9d9;
  font-size: 16px;
  font-weight: bold;
  display: inline-block;
  width: 20px;
  text-align: center;
}

/* 状态合并规则提示样式 */
.status-merge-alert {
  margin-bottom: 16px;
}
</style>
